package com.payment.system.service.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.payment.common.base.AjaxResult;
import com.payment.common.type.OrderNoPrefix;
import com.payment.common.type.OrderStatus;
import com.payment.common.type.ShipmentStatus;
import com.payment.common.utils.DateUtils;
import com.payment.common.utils.StringUtils;
import com.payment.system.domain.Merchant;
import com.payment.system.domain.ShoppingAddress;
import com.payment.system.domain.ShoppingOrder;
import com.payment.system.domain.ShoppingOrderProduct;
import com.payment.system.domain.ShoppingOrderShipment;
import com.payment.system.domain.ShoppingProduct;
import com.payment.system.domain.SysUser;
import com.payment.system.mapper.MerchantMapper;
import com.payment.system.mapper.ShoppingAddressMapper;
import com.payment.system.mapper.ShoppingOrderMapper;
import com.payment.system.mapper.ShoppingOrderProductMapper;
import com.payment.system.mapper.ShoppingOrderShipmentMapper;
import com.payment.system.mapper.ShoppingProductMapper;
import com.payment.system.service.IShoppingOrderService;


/**
 * 商城订单 服务层实现
 *
 * @author payment
 * @date 2019-01-22
 */
@Service
public class ShoppingOrderServiceImpl implements IShoppingOrderService {
    private static final Logger log = LoggerFactory.getLogger(ShoppingOrderServiceImpl.class);
    @Autowired
    private ShoppingOrderMapper shoppingOrderMapper;

    @Autowired
    private ShoppingProductMapper shoppingProductMapper;

    @Autowired
    private ShoppingOrderProductMapper shoppingOrderProductMapper;

    @Autowired
    private MerchantMapper merchantMapper;

    @Autowired
    private ShoppingOrderShipmentMapper shoppingOrderShipmentMapper;

    @Autowired
    private ShoppingAddressMapper shoppingAddressMapper;

    /**
     * 查询商城订单信息
     *
     * @param id 商城订单ID
     * @return 商城订单信息
     */
    @Override
    public ShoppingOrder selectShoppingOrderById(String id) {
        ShoppingOrder order = shoppingOrderMapper.selectShoppingOrderById(id);
        List<ShoppingOrderProduct> productList = shoppingOrderProductMapper.selectShoppingOrderProductByOrderId(id);
        order.setOrderProductList(productList);
        return order;
    }


    /**
     * 查询商城订单列表
     *
     * @param shoppingOrder 商城订单信息
     * @return 商城订单集合
     */
    @Override
    public List<ShoppingOrder> selectShoppingOrderList(ShoppingOrder shoppingOrder) {
        return shoppingOrderMapper.selectShoppingOrderList(shoppingOrder);
    }

    /**
     * 新增商城订单
     *
     * @param shoppingOrder 商城订单信息
     * @return 结果
     */
    @Override
    public int insertShoppingOrder(ShoppingOrder shoppingOrder) {
        return shoppingOrderMapper.insertShoppingOrder(shoppingOrder);
    }

    /**
     * 修改商城订单
     *
     * @param shoppingOrder 商城订单信息
     * @return 结果
     */
    @Override
    public int updateShoppingOrder(ShoppingOrder shoppingOrder) {
        return shoppingOrderMapper.updateShoppingOrder(shoppingOrder);
    }

    protected int saveShoppingOrderShipment(String orderId, String freCompanyName, String trackingNumber, SysUser user) {
        ShoppingOrder order = shoppingOrderMapper.selectShoppingOrderById(orderId);
        ShoppingOrderShipment shipment = shoppingOrderShipmentMapper.selectShoppingOrderShipmentByOrderId(orderId);
        if (order == null || shipment == null) {
            return 0;
        }
        shipment.setTrackingNumber(trackingNumber);
        shipment.setFreCompanyName(freCompanyName);
        shipment.setShipmentName(user.getUserName());
        shipment.setState(ShipmentStatus.YES.getCode());
        return shoppingOrderShipmentMapper.updateShoppingOrderShipment(shipment);
    }

    ////app端 提交订单(单商品购买) 生成订单
    @Override
    public AjaxResult submitOrder(String merchantId, String productId, Integer buyNumber, String addressId) {
        if (StringUtils.isEmpty(merchantId) || StringUtils.isEmpty(productId) || buyNumber == null || StringUtils.isEmpty(addressId)) {
            return AjaxResult.error(1, "缺失参数!");
        }
        if (buyNumber <= 0) {
            return AjaxResult.error(2, "购买数量不能小于0!");
        }
        Merchant merchant = merchantMapper.selectMerchantById(merchantId);
        if (merchant == null) {
            return AjaxResult.error(3, "该用户不存在!");
        }
        if (merchant.getLevel()==0) {
            return AjaxResult.error(3, "您尚未实名请先去实名认证!");
        }
        ShoppingProduct product = shoppingProductMapper.selectShoppingProductById(productId);
        if (product == null) {
            return AjaxResult.error(4, "该商品不存在!");
        }
        try {
            String orderId = StringUtils.randomUUID();
            String orderNumber = "";
            //保存订单商品表
            //判断商品是否是商户商品
                orderNumber = OrderNoPrefix.PREFIX_SHANGHU.getCode() + DateUtils.dateTimeNow() + new Random().nextInt(10000) + "";

            boolean orderProductResult = this.saveOrderProduct(product, orderNumber, orderId, buyNumber);
            //保存订单表 /订单配送
            boolean orderResult = this.saveOrder(product, orderNumber, merchant, orderId, buyNumber, 1, addressId);

            if (orderResult && orderProductResult) {
                ShoppingOrder order = this.selectShoppingOrderById(orderId);
                List<ShoppingOrderProduct> orderProductList = shoppingOrderProductMapper.selectShoppingOrderProductByOrderId(orderId);
                order.setOrderProductList(orderProductList);
                ShoppingAddress address = shoppingAddressMapper.selectShoppingAddressById(addressId);

                Map<String, Object> map = new HashMap<String, Object>(16);
                map.put("order", order);
                if (address == null) {
                    map.put("userName", merchant.getMerchantCnName());
                    map.put("addressDetails", "江西大厦4层4090");
                    map.put("province", "河北省");
                    map.put("area", "新华区");
                    map.put("city", "石家庄市");
                    map.put("phone", "400-808-3305");
                } else {
                    map.put("userName", address.getUserName());
                    map.put("addressDetails", address.getAddressDetails());
                    map.put("province", address.getProvince());
                    map.put("area", address.getArea());
                    map.put("city", address.getCity());
                    map.put("phone", address.getPhone());
                }


                return AjaxResult.successAndData("提交订单成功!", map);
            }
            return AjaxResult.error(6, "提交订单失败!");
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("app提交订单失败=" + e.toString());
            return AjaxResult.error("提交订单失败!请联系客服咨询");
        }
    }


    ////app端  订单列表
    @Override
    public AjaxResult selectShoppingOrderListByMerchantId(String merchantId, String orderStatus, Integer pageNum, Integer pageSize) {
        if (StringUtils.isEmpty(merchantId) || pageNum == null || pageSize == null) {
            return AjaxResult.error(1, "获取订单列表失败：缺失参数！");
        }
        Merchant merchant = merchantMapper.selectMerchantById(merchantId);
        if (merchant == null) {
            return AjaxResult.error(2, "获取订单列表失败：该用户不存在！");
        }
        List<ShoppingOrder> list = shoppingOrderMapper.selectShoppingOrderListByMerchantId(merchantId, orderStatus, pageNum * pageSize, pageSize);
        return AjaxResult.successAndData("获取订单信息成功！", list);
    }

    // 修改订单状态 用户id  订单id
    @Override
    public AjaxResult updateOrderStatusByOrederId(String orderId) {
        if (StringUtils.isEmpty(orderId)) {
            return AjaxResult.error(1, "缺失参数");
        }
        ShoppingOrder order = shoppingOrderMapper.selectShoppingOrderById(orderId);
        if (order == null) {
            return AjaxResult.error(2, "该订单不存在");
        }
        if (StringUtils.equals(order.getOrderStatus(), OrderStatus.PAID.getCode())) {
            return AjaxResult.error(3, "该订单已支付不能取消");
        }
        if (StringUtils.equals(order.getOrderStatus(), OrderStatus.CANCEL.getCode())) {
            return AjaxResult.error(4, "该订单已经是取消状态");
        }
        int r = shoppingOrderMapper.updateOrderStatusById(orderId, OrderStatus.CANCEL.getCode());
        if (r > 0) {
            return AjaxResult.success("取消订单成功");
        } else {
            return AjaxResult.error(5, "取消订单失败");
        }

    }

    ////app 删除订单  修改订单删除状态
    @Override
    public AjaxResult updateOrderDelStatusByOrederId(String orderId) {
        if (StringUtils.isEmpty(orderId)) {
            return AjaxResult.error(1, "缺失参数");
        }

        int r = shoppingOrderMapper.updateOrderDelStatusByOrederId(orderId);
        if (r > 0) {
            return AjaxResult.success("删除订单成功");
        } else {
            return AjaxResult.error(2, "删除订单失败");
        }
    }


    //保存订单商品
    protected boolean saveOrderProduct(ShoppingProduct product, String orderNumber, String orderId, Integer buyNumber) {
        ShoppingOrderProduct orderProduct = new ShoppingOrderProduct();
        orderProduct.setId(StringUtils.randomUUID());
        orderProduct.setOrderId(orderId);
        orderProduct.setProductId(product.getId());
        orderProduct.setName(product.getProductName());
        orderProduct.setShipmentAmount(new BigDecimal(0));
        if (!product.getImg().equals("")) {
            String[] img = product.getImg().split(";");
            orderProduct.setPicImg(img[0]);
        }
        orderProduct.setPrice(product.getPrice());
        orderProduct.setBuyNumber(buyNumber);
        BigDecimal num = new BigDecimal(buyNumber);
        orderProduct.setScore(product.getShowScore());
        orderProduct.setProductAmount(product.getPrice().multiply(num));
        orderProduct.setProductScore(0);
        orderProduct.setOrderNumber(orderNumber);
        int orderProductResult = shoppingOrderProductMapper.insertShoppingOrderProduct(orderProduct);
        if (orderProductResult > 0) {
            return true;
        }
        return false;
    }

    //保存订单配送表
    protected int saveShoppingOrderShipment(String addressId, String orderNo, String orderId) {
        ShoppingOrderShipment orderShipment = new ShoppingOrderShipment();
        ShoppingAddress address = shoppingAddressMapper.selectShoppingAddressById(addressId);
        orderShipment.setId(StringUtils.randomUUID());
        orderShipment.setOrderNumber(orderNo);
        orderShipment.setOrderId(orderId);
        orderShipment.setDel(1);
        if (address != null) {
            orderShipment.setProvinceName(address.getProvince());
            orderShipment.setCityName(address.getCity());
            orderShipment.setDistrictName(address.getArea());
            orderShipment.setUserAdress(address.getAddressDetails());
            orderShipment.setUserZipcode(address.getPostCode());
            orderShipment.setMerchantId(address.getMerchantId());
            orderShipment.setUserName(address.getUserName());
            orderShipment.setUserPhone(address.getPhone());
            orderShipment.setState(ShipmentStatus.NO.getCode());
        }
        return shoppingOrderShipmentMapper.insertShoppingOrderShipment(orderShipment);
    }

    //保存订单
    protected boolean saveOrder(ShoppingProduct product, String orderNumber, Merchant merchant, String orderId, Integer buyNumber, int type, String addressId) {
        ShoppingOrder order = new ShoppingOrder();
        order.setId(orderId);
        order.setOrderNumber(orderNumber);
        order.setMerchantId(merchant.getId());
        order.setMerchantNo(merchant.getMerchantNo());
        order.setMerchantName(merchant.getMerchantCnName());
        order.setOrderStatus(OrderStatus.NO_PAY.getCode());
        order.setPayType("10G");
        if (type == 1) {
            order.setShipmentAmount(new BigDecimal(0));
            BigDecimal num = new BigDecimal(buyNumber);
            order.setOrderAmount(product.getPrice().multiply(num));
            order.setPayAmount(order.getOrderAmount().add(order.getShipmentAmount()));
            order.setOrderScore(0);
            order.setBuyNumber(buyNumber);
        }

        //保存订单配送 String addressId,String orderNo,String orderId
        //999 为自取商品
        if (StringUtils.equals(addressId, "999")) {
            order.setDelivery("10A");
        } else {
            //配送
            order.setDelivery("10B");
            saveShoppingOrderShipment(addressId, orderNumber, orderId);
        }
        int orderResult = shoppingOrderMapper.insertShoppingOrder(order);
        if (orderResult > 0) {
            return true;
        }
        return false;
    }


}
